package com.zoo.wuhua.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <b>文件上传</b><br>
 *
 * @author zhangli7@yusys.com.cn
 * @since 2019年11月1日 下午12:40:11
 */
@RestController
public class FileUploadController {

    private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyyMMdd");

    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request) {
        // 获取当前项目的绝对磁盘路径，C:\Users\yanfa148\AppData\Local\Temp\tomcat-docbase.284460534597795763.7777\
        // uploadFile\
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
        String currentDate = FORMAT.format(new Date());
        File folder = new File(realPath + currentDate);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String originalName = uploadFile.getOriginalFilename();
        // 22932efc-2950-41d5-a357-6cd78d8d2c4e.txt
        String newName = UUID.randomUUID().toString() + originalName.substring(originalName.indexOf("."));
        try {
            uploadFile.transferTo(new File(folder, newName));
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/uploadFile/" + currentDate + newName;
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

}
